<template>
  <div>
    <div class="search-bar" style="display: flex; justify-content: flex-end; margin-bottom: 20px;">
      <el-input v-model="posttitle" style="width: 300px; margin-right: 10px;" clearable @clear="clearSearch" placeholder="请输入想搜索的帖子标题？"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      <el-button type="danger" icon="el-icon-edit-outline" @click="sendPost">我要发帖</el-button>
    </div>

    <el-row :gutter="15" class="content-row">
      <el-col :span="4" class="sidebar">
        <h4 class="section-title">
          <i class="el-icon-collection"></i>
          <span class="section-title-text">帖子类型</span>
        </h4>
        <div class="sidebar-content">
          <p class="xw-enlarge" v-for="type in ['全部', ...postTypeData]" :key="type" @click="changeType(type)">
            <i class="el-icon-collection"></i>
            <span>{{ type }}</span>
          </p>
        </div>
      </el-col>


      <el-col :span="16" class="main-content">
        <h4 class="section-title">
          <i class="el-icon-collection"></i>
          <span class="section-title-text">帖子内容</span>
        </h4>
        <ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto;">
          <li v-for="(item, index) in tableData.slice(0, count)" :key="index" class="post-item">
            <div class="post-item-content">
              <h4 class="ellipsis post-title" @click="toDetail(item)">{{ item.title }}</h4>
              <p class="ellipsis post-description">{{ item.content }}</p>
              <p class="post-meta">
                <i class="el-icon-s-custom"></i>
                <span>{{ item.sendUserName }}</span>
                <span>{{ item.sendTime | dateFormatHms }}</span>
                <el-tag class="post-tag" type="mini">{{ item.type }}</el-tag>
              </p>
            </div>
            <div class="post-image">
              <el-avatar :size="60" :src="item.sendUserPic" @error="errorHandler" />
              <div class="post-actions">
                <!-- 通过文章标题获取 ID 进行操作 -->
                <el-button icon="el-icon-edit" type="text" @click="edit(item.title)"></el-button>
                <el-popconfirm
                    title="这是一段内容确定删除吗？"
                    @confirm="del(item.title)"
                >
                  <el-button slot="reference" icon="el-icon-delete" type="text" style="margin-left: 10px;"></el-button>
                </el-popconfirm>
              </div>
            </div>
          </li>
        </ul>
      </el-col>

      <el-col :span="4" class="sidebar high-rank">
        <h4 class="section-title">
          <i class="el-icon-trophy"></i>
          <span class="section-title-text">高赞帖子</span>
        </h4>
        <div class="high-rank-content">
          <ul>
            <li v-for="(post, index) in highRankPosts" :key="index" class="high-rank-item">
              <h4 class="ellipsis xw-enlarge"
                  @click="toDetailthumb(post)"
                  style="cursor: pointer; color: rgba(255,64,109,0.93); font-weight: bold;">
                {{ post.title }}
              </h4>
            </li>
          </ul>
        </div>
      </el-col>

    </el-row>

    <SendPost ref="SendPost" @sendSuccess="load"></SendPost>

    <my-drawer ref="MyDrawer" :row="selectRow" @saveOrUpdate="update">
      <template #default>
        <el-form label-position="top" class="post-form">
          <el-form-item label='标题'>
            <el-input placeholder='请输入发布的帖子标题'
                      v-model='selectRow.title'></el-input>
          </el-form-item>
          <el-form-item label="帖子类型">
            <el-select v-model="selectRow.type" placeholder="请选择帖子类型">
              <el-option label="C语言" value="C语言"></el-option>
              <el-option label="HTML" value="HTML"></el-option>
              <el-option label="JAVA" value="JAVA"></el-option>
              <el-option label="Python" value="Python"></el-option>
              <el-option label="云计算" value="云计算"></el-option>
              <el-option label="软件工程" value="软件工程"></el-option>
              <el-option label="计算机科学与技术" value="计算机科学与技术"></el-option>
              <el-option label="信息安全" value="信息安全"></el-option>
              <el-option label="大数据" value="大数据"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label='发布内容'>
            <vue-editor v-model="selectRow.content"></vue-editor>
          </el-form-item>
        </el-form>
      </template>
    </my-drawer>

    <el-backtop target=".xw-container"></el-backtop>
  </div>
</template>

<script>
import SendPost from "@/components/SendPost.vue";
import MyDrawer from "@/components/MyDrawer.vue";
import { VueEditor } from "vue2-editor";

export default {
  data() {
    return {
      posttitle: '',
      count: 10,
      pageSizeArr: [10, 20, 30, 40],
      tableData: [],
      postTypeData: [],
      highRankPosts: [], // 高赞帖子的列表
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
        q: {}
      },
      total: 0,
      user: JSON.parse(localStorage.getItem("user")),
      selectRow: {
        title: '',
        type: '',
        content: ''
      }  // 用于存储选中的文章
    };
  },
  mounted() {
    this.load()
  },
  components: { MyDrawer, SendPost, VueEditor },
  methods: {
    toDetailthumb(post) {
      const url = this.$router.resolve({ name: 'PostCodeDetail', params: { id: post.linkId } }).href;
      window.open(url);
    },
    toDetail(item) {
      const url = this.$router.resolve({ name: 'PostCodeDetail', params: { id: item.id } }).href;
      window.open(url);
    },
    sendPost() {
      this.$refs.SendPost.open()
    },
    clearSearch() {
      this.posttitle = '';  // 清空输入框
      this.pageRequest.q = {};  // 清空搜索条件
      this.load();  // 重新加载数据
    },

    search() {
      this.pageRequest.pageNum = 1;  // 重置页码
      if (this.posttitle.trim() === '') {
        // 如果没有输入标题，清空查询条件，显示所有帖子
        this.pageRequest.q = {};
      } else {
        // 如果输入了标题，按照标题搜索
        this.pageRequest.q.title = this.posttitle;
      }
      this.load();  // 重新加载数据
    },
    edit(title) {
      // 根据标题查找文章并进行编辑
      const post = this.tableData.find(item => item.title === title);
      if (post) {
        this.selectRow = post;
        this.$refs.MyDrawer.open(this.selectRow);
      }
    },
    update() {
      this.request.post("/postCode", this.selectRow).then(res => {
        if (res.code === '200') {
          this.messageSuccess("修改成功");
          this.$refs.MyDrawer.close();  // 关闭抽屉
          this.load();  // 重新加载数据
        } else {
          this.messageError(res.msg);  // 显示错误消息
        }
      });
    },
    del(title) {
      // 根据标题查找文章并进行删除
      const post = this.tableData.find(item => item.title === title);
      if (post) {
        this.request.delete(`/postCode/${post.id}`).then(res => {
          if (res.code === '200') {
            this.messageSuccess("删除成功");
            this.load();  // 重新加载数据
          } else {
            this.messageError("删除失败");
          }
        });
      }
    },
    changeType(type) {
      if (type === '全部') {
        this.pageRequest.q.type = '';  // 清空类型筛选
      } else {
        this.pageRequest.q.type = type;  // 设置为选中的类型
      }
      this.load();  // 重新加载帖子
    },
    load() {
      this.request.post("/postCode/page", this.pageRequest).then(res => {
        if (res.code === '200') {
          // 对帖子列表根据 sendTime 进行倒序排序
          this.tableData = res.data.list.sort((a, b) => new Date(b.sendTime) - new Date(a.sendTime));
          this.total = res.data.total;
        }
      });

      // 加载高赞帖子数据
      this.request.get("/thumbs/highRankPosts").then(res => {
        if (res.code === '200') {
          this.highRankPosts = res.data; // 假设后端接口返回按点赞数排序的高赞帖子
        }
      });
      this.request.get("/postCode/postType").then(res => {
        if (res.code === '200') {
          this.postTypeData = res.data;
        }
      });
    },
    loadMore() {
      if (this.count < this.tableData.length) {
        this.count += 10;  // 每次增加10个帖子
      }
    },
    errorHandler() {
      // 头像加载失败时返回灰色
      return true;
    }
  }
}
</script>

<style scoped>
.search-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.search-btn, .post-btn {
  margin-left: 10px;
  padding: 8px 15px;
}

.search-btn {
  background-color: #409EFF;
  border-color: #409EFF;
}

.post-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.content-row {
  display: flex;
  justify-content: center;
}

.sidebar {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sidebar .section-title {
  font-size: 18px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.sidebar .section-title-text {
  margin-left: 8px;
}

.sidebar-content {
  max-height: 50vh;
  overflow-y: auto;
  padding: 10px;
}

.sidebar-content p {
  cursor: pointer;
  margin: 8px 0;
  padding: 8px;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

.sidebar-content p:hover {
  background-color: #f0f0f0;
}

.main-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.infinite-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.post-item {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #e4e6eb;
}

.post-item-content {
  width: 80%;
}

.post-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  cursor: pointer;
}

.post-description {
  font-size: 14px;
  color: #777;
  margin-top: 5px;
}

.post-meta {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
}

.post-tag {
  margin-left: 10px;
}

.post-image img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.el-tag {
  transition: background-color 0.3s ease, color 0.3s ease;
}

.el-tag:hover {
  background-color: #f56c6c;
  color: #fff;
}

.el-icon-thumb {
  margin-right: 5px;
}

/* 将 el-backtop 定位在右下角 */
.el-backtop {
  right: 20px;
  bottom: 20px;
  position: absolute;
  z-index: 10;
}

/* 自定义头像样式 */
.el-avatar {
  background-color: #e0e0e0; /* 默认灰色背景 */
  color: #fff;
}
</style>
